﻿@using Gurux.DLMS.AMI.Shared.DIs

@using Gurux.DLMS.AMI.Shared.DTOs.Schedule
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.AMI.Module
@using System.Globalization

@attribute [Authorize(Roles = GXRoles.Admin + "," + GXRoles.Schedule)]
@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier

@if (Active != null)
{
    <EditForm Model="@Active">
        <DataAnnotationsValidator />
        <GXValidator @ref="_scheduleValidator" OnValidate="OnValidate" />
        <div class="row">
            <div style="width:100%">
                <div class="form-group">
                    <InputNullableSwitch Text="@Properties.Resources.Active" @bind-Value="Active.Active" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Name</label>
                    <InputText id="name" disabled="@IsDeleting" @bind-Value="Active.Name" class="form-control"
                               placeholder=@Properties.Resources.ScheduleName />
                    <ValidationMessage For="@(() => Active.Name)" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.Description</label>
                    <InputText id="name" disabled="@IsDeleting" class="form-control"
                               @bind-Value="Active.Description" />
                </div>
                <div class="form-group">
                    <label>@Properties.Resources.ScheduleExecutionTime</label>
                    <input type="text" id="start" disabled="@IsDeleting" value="@GetDateTime()" class="form-control"
                           @onchange="@((ChangeEventArgs __e) => SetDateTime(Convert.ToString(__e.Value)))" placeholder=@Properties.Resources.ScheduleExecutionTime />
                    <ValidationMessage For="@(() => Active.Start)" />
                </div>
                @if (Active.CreationTime != DateTime.MinValue)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.CreationTime</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="generation" readonly="readonly" class="form-control"
                                   @bind-Value="Active.CreationTime" />
                    </div>
                }
                @if (Active.Updated != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Updated</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="generation" readonly="readonly" class="form-control"
                                   @bind-Value="Active.Updated" />
                    </div>
                }
                @if (Active.Removed != null)
                {
                    <div class="form-group">
                        <label>@Properties.Resources.Removed</label>
                        <InputDate Type="@InputDateType.DateTimeLocal" id="removed" class="form-control"
                                   @bind-Value="Active.Removed" />
                    </div>
                }
                @if (action == CrudAction.Delete)
                {
                    <hr />
                    <p>
                    </p>
                    <div class="form-group">
                        <InputRadioGroup @bind-Value="DeleteTarget">
                            <InputRadio Value="false">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDisableQuestion</label><br>
                            <InputRadio Value="true">
                            </InputRadio>
                            <label>@Properties.Resources.TargetDeleteQuestion</label>
                        </InputRadioGroup>
                        <br />
                    </div>
                }
            </div>
        </div>
    </EditForm>
}
@code {
    private bool DeleteTarget;
    [CascadingParameter]
    private ScheduleTab? Parent { get; set; }

    private GXSchedule? _active;

    private GXSchedule? Active
    {
        get
        {
            if (Parent?.Active != null)
            {
                return Parent.Active;
            }
            return _active;
        }
    }

    private GXValidator? _scheduleValidator;

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    private CrudAction action;
    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public Guid? Id { get; set; }

    public string? IsDeleting
    {
        get
        {
            if (action != CrudAction.Delete)
            {
                return null;
            }
            return "disabled";
        }
    }

    /// <summary>
    /// Convert date-string from invaliant culture to user format.
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    string? GetDateTime()
    {
        try
        {
            if (!string.IsNullOrEmpty(Active?.Start))
            {
                GXDateTime tm = new GXDateTime(Active.Start);
                return tm.ToFormatString();
            }
            return "";
        }
        catch (Exception)
        {
            return Active?.Start;
        }
    }
    /// <summary>
    /// Date time is serialized to invariant culture.
    /// </summary>
    /// <param name="value"></param>
    void SetDateTime(string value)
    {
        try
        {
            if (Active != null)
            {
                Notifier?.ClearStatus();
                GXDateTime tm = new GXDateTime(value);
                Active.Start = tm.ToFormatString();
            }
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            if (Active == null && Id != null)
            {
                //Get schedule data.
                var tmp = (await Http.GetAsJsonAsync<GetScheduleResponse>(string.Format("api/Schedule?id={0}", Id)));
                if (tmp?.Item != null)
                {
                    _active = tmp.Item;
                }
                else
                {
                    NavigationManager.NavigateTo("404");
                }
            }
            if (Active == null)
            {
                throw new ArgumentException(Properties.Resources.InvalidTarget);
            }
            action = ClientHelpers.GetAction(Action);
            if (action == CrudAction.Delete)
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Remove, Icon = "oi oi-trash", OnClick = OnSave });
            }
            else
            {
                Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Save, Icon = "oi oi-pencil", OnClick = OnSave });
            }
            Notifier.AddMenuItem(new GXMenuItem() { Text = Properties.Resources.Cancel, Icon = "oi oi-action-undo", OnClick = OnCancel });
            Notifier.UpdateButtons();
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Validate the schedule content.
    /// </summary>
    /// <param name="sender"></param>
    private void OnValidate(GXValidator sender)
    {
        if (Active != null)
        {
            if (string.IsNullOrEmpty(Active.Name))
            {
                sender.AddError(() => Active.Name, "Invalid name.");
            }
            //Check schedule start time.
            try
            {
                GXDateTime tm = new GXDateTime(Active.Start);
            }
            catch (Exception ex)
            {
                sender.AddError(() => Active.Start, "Invalid start time.");
            }
        }
    }

    /// <summary>
    /// Save Active.
    /// </summary>
    public async void OnSave()
    {
        if (!(Parent != null && await Parent.AcceptChanges(false)))
        {
            try
            {
                _scheduleValidator?.ClearErrors();
                if (Active == null)
                {
                    throw new Exception(Properties.Resources.InvalidTarget);
                }
                if (_scheduleValidator != null && !_scheduleValidator.Validate())
                {
                    return;
                }
                Notifier.ProgressStart();
                Notifier.ClearStatus();
                if (action == CrudAction.Delete)
                {
                    await Http.PostAsJson<RemoveScheduleResponse>("api/Schedule/Delete",
                        new RemoveSchedule()
                            {
                                Ids = new Guid[] { Active.Id },
                                Delete = DeleteTarget
                            }
                        );
                }
                else
                {
                    string address;
                    if (action == CrudAction.Create)
                    {
                        address = "api/Schedule/Add";
                    }
                    else if (action == CrudAction.Update)
                    {
                        address = "api/Schedule/Update";
                    }
                    else
                    {
                        throw new Exception(Properties.Resources.InvalidTarget);
                    }
                    string? dt = Active.Start;
                    try
                    {
                        //Convert start time from UI culture to invariant culture.
                        Active.Start = new GXDateTime(Active.Start).ToFormatString(CultureInfo.InvariantCulture);
                        await Http.PostAsJson<UpdateScheduleResponse>(address, new UpdateSchedule()
                            {
                                Schedules = new List<GXSchedule>() { Active }
                            });
                    }
                    finally
                    {
                        Active.Start = dt;
                    }
                }
                ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
            }
            catch (AccessTokenNotAvailableException exception)
            {
                exception.Redirect();
            }
            catch (Exception ex)
            {
                Notifier?.ProcessError(ex);
            }
            finally
            {
                Notifier.ProgressEnd();
                StateHasChanged();
            }
        }
    }

    /// <summary>
    /// Cancel update.
    /// </summary>
    private void OnCancel()
    {
        if (!(Parent != null && Parent.AcceptChanges(true).Result))
        {
            //Close schedule UI.
            ClientHelpers.NavigateToLastPage(NavigationManager, Notifier);
        }
    }
}